// 区分环境 ,HbuilderX编辑运行时dev开发环境，发行后自动时生成环境

import Vue from 'vue'
class Model {
  //定义接口
  api(opts = {}) {
    //监听网络链接
    uni.onNetworkStatusChange((res) => {
      if (!res.isConnected) {
        uni.showToast({
          title: '网络连接不可用！',
          icon: 'none'
        });
      }
      return false
    });
	let baseUrl = Vue.prototype.baseUrl
    //定义参数对象
    if (!opts.method) opts.method = 'get'
    if (opts.domain) baseUrl = opts.domain
    // token
    let token = ''
    // 鉴权
    // let authorize = ''
    if (uni.getStorageSync('token')) {
		token = uni.getStorageSync('token')
	}
    // if (uni.getStorageSync('Authorization')) authorize = uni.getStorageSync('Authorization')
    // 前端自定义token失效
    // if (token == '' || token == undefined || token == null) {
    //   uni.showToast({
    //     title: '账号已过期，请重新登录',
    //     icon: 'none',
    //     complete: function() {
    //       uni.reLaunch({
    //         url: '/pages/login/index'
    //       });
    //     }
    //   });
    // }
	if(!opts.header){
		opts.header = {
		  'Content-Type': 'application/json; charset=UTF-8'
		}
	}
    
	opts.header['X-Access-Token'] = token;
    // 删除鉴权
    // if (opts.noAuth) {
    //   delete header.Authorization
    // }
	// console.log(opts)
	// return false;
    return new Promise((resolve, reject) => {
      uni.request({
        url: baseUrl + opts.url,
        data: opts.data,
        method: opts.method,
        header: opts.header,
        success: res => {
		   if (res.data.code == 200) {
				resolve(res.data);
			}
			// token过期
			else if (res.data.code === -9998) {
				uni.showToast({
					icon:'none',
					title: res.data.message,
					duration: 5000,
				});
				uni.removeStorageSync('token');
			    setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}, 1000)
				reject(res.data);
			} else {
				uni.hideLoading()
				console.log(res.data)
				uni.showToast({
					title: res.data.message || res.data.msg,
					icon: 'none',
					duration: 1500
				});
				reject(res.data);
			}
        
        },
        fail: () => {
          console.log('请求失败,请稍候重试');
          uni.hideLoading();
          uni.showToast({
            title: '网络拥挤、请稍后再试！',
            icon: 'none',
            duration: 1500
          });
        }
      });
    })
  }

  get(options = {}) {
    options.method = 'GET'
    return this.api(options)
  }
  post(options = {}) {
    options.method = 'POST'
    return this.api(options)
  }
  put(options = {}) {
    options.method = 'PUT'
    return this.api(options)
  }
  delete(options = {}) {
    options.method = 'DELETE'
    return this.api(options)
  }
}

export default Model